<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-20 14:35:28
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2023-01-04 09:36:21
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Edit.vue
 * Copyright (c) 2023 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { PropType, h, reactive, ref } from 'vue'
// import { adminFaUserListApi } from '@/api/fa/user'
import { useIcon } from '@/hooks/web/useIcon'
import { spForageListApi, spForageSpecsListApi } from '@/api/sp/food'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
// import { useForm } from '@/hooks/web/useForm'
import EarconRefer from './EarconRefer.vue'

import Food from '../components/Dialog.vue'
import {
  spForageInOutActualNumberEditApi,
  spForageInOutDetailedAddAdminApi,
  spForageInOutDetailedDelApi,
  spForageInOutOrderSeeApi,
  spForageInOutRfidBatchAddApi
} from '@/api/cy/FoodGoTo'
import { spForageSpecsSeeApi } from '@/api/cy/DrugGoTo'

// const saveLoading = ref(false)
const icon = useIcon({ icon: 'material-symbols:add-circle-outline' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })
const iconOk = useIcon({ icon: 'flat-color-icons:ok' })
// 获取操作员
// const getOperator = async (new_data) => {
//   const res = await adminFaUserListApi({ ...new_data, source: 'operator' })
//     .catch(() => {})
//     .finally(() => {})
//   if (res) {
//     return res
//   }
// }

/****************************** 变量 start ******************************/
const data = ref<any>({})

const d_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'forage_id',
    label: '饲料档案',
    width: 150
  },
  {
    field: 'forage_specs_id',
    label: '饲料规格',
    width: 150
  },
  // {
  //   field: 'state',
  //   label: '状态',
  //   width: 150,
  //   componentProps: {
  //     options: dict.quarantine_order_state
  //   }
  // },
  {
    field: 'apply_number',
    label: '申请数量',
    width: 150
  },
  {
    field: 'actual_number',
    label: '实际数量',
    width: 150
  },
  {
    field: 'rfid_number',
    label: 'rfid数量',
    width: 150
  },
  {
    field: 'amount',
    label: '采购金额',
    width: 150
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: '操作'
  }
])

// const { methods } = useForm({
//   d_columns: d_columns
// })
/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  },
  id: {
    type: String,
    default: null
  }
})
console.log(props.currentRow)
/****************************** 组件参数 end ******************************/

/****************************** 函数方法 start ******************************/
const getPastureSee = async () => {
  if (props.id) {
    const res = await spForageInOutOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value.detailed = await res.data.detailed
      // await methods.setValues(data.value)
    }
  }
}
const d_id = ref(0)
let dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')

let ss = reactive([])
const Addd = async (r, row) => {
  ss = r.split(/[,，]/)
  console.log(ss, '2', row)

  // var arr = ['A', '', 'B', null, undefined, 'C', '  ', 'D', 'feiniaomy.com']
  let ri: any = ss.filter(function (s) {
    return s && s.trim()
  })
  console.log(ri, 'ri')

  const res = await spForageInOutRfidBatchAddApi({
    forage_in_out_detailed_id: row.id,
    rfid_detailed: ri
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    // await methods.setValues(data.value)
    await getPastureSee()
  }
}
const Rfid = ref('')
// let rfid = ref<any>()
// 点击弹窗
const action = async (type: string, row) => {
  actionType.value = type
  switch (type) {
    case 'mu':
      dialogTitle.value = '选择牧场 (双击选择)'
      dialogVisible.value = true
      // data.value.detailed = []

      break
    case 'add':
      dialogTitle.value = '新增'
      Rfid.value = row
      dialogVisible.value = true
      break
    case 'add+':
      ElMessageBox.prompt('添加Rfid, 以逗号分隔', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          // rfid.value = value.split(',')
          Addd(value, row)
          ElMessage({
            type: 'success',
            message: `添加成功:${value}`
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消'
          })
        })
      break
    case 'see':
      dialogTitle.value = '查看'
      dialogVisible.value = true
      break
    case 'add_d':
      d_id.value++
      data.value.detailed.push({ state: 1, amount: 0.0 })
      break
    case 'del_d':
      // 明细删除
      const de = await spForageInOutDetailedDelApi({
        id: row.id
      })
        .catch(() => {})
        .finally(() => {})
      if (de) {
        getPastureSee()
        // return res
      }
      // let row_i = data.value.detailed.findIndex((item) => {
      //   return item.d_id == row.d_id
      // })
      // data.value.detailed.splice(row_i, 1)
      console.log(row.id, 'row')
      break
    case 'ok':
      if (!row.forage_specs_id) {
        ElMessage('请选择饲料规格')
        break
      } else if (!row.forage_id) {
        ElMessage('请选择饲料档案')
        break
      } else if (!row.apply_number) {
        ElMessage('请填入申请数量')
        break
      } else if (props.currentRow.type == '1' && !row.amount) {
        ElMessage('请填入采购金额')
        break
      }
      const GG = await spForageSpecsSeeApi({ id: row.forage_specs_id })

      if (GG) {
        console.log(Number(GG.data.available_stock) - Number(row.apply_number))
        if (
          Number(GG.data.available_stock) - Number(row.apply_number) <= 0 &&
          props.currentRow.type == '2'
        ) {
          ElNotification({
            title: '通知',
            message: h('i', { style: 'color: teal' }, '出库数量不足，从新选择或者修改数量！！！')
          })
          break
        }
        // return res
      }
      row.state = 2
      console.log(row, props)
      const res = await spForageInOutDetailedAddAdminApi({
        forage_in_out_order_id: props.id,
        forage_id: row.forage_id,
        forage_specs_id: row.forage_specs_id,
        amount: row.amount,
        apply_number: row.apply_number,
        actual_number: row.actual_number
      })
        .catch(() => {})
        .finally(() => {})
      if (res) {
        getPastureSee()
        // return res
      }
      break
    case 'rfid_number':
      console.log(row, 'rfid_number')
      const re = await spForageInOutActualNumberEditApi({
        forage_in_out_detailed_id: row.id,
        actual_number: row.actual_number
      })
        .catch(() => {})
        .finally(() => {})
      if (re) {
        await getPastureSee()
      }
      break
    default:
      console.log('未知类型')
  }
}

// 饲料档案Api
const getDanganListApi = async (new_data) => {
  let formData: any = props.currentRow
  console.log(!!formData.pasture_org_name, formData, new_data, 'rrr')
  if (!!formData.pasture_org_id) {
    // console.log('formData', !formData.customer_id, new_data, adminFaEarconListApi)
    const res = await spForageListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      return res
    }
  } else {
    ElMessage({
      message: '请选择牧场',
      type: 'warning'
    })
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
}

// 饲料规格Api
const getGuigeListApi = async (new_data) => {
  let formData: any = props.currentRow
  console.log(!!formData.pasture_org_name, formData, new_data, 'rrr')
  if (!!formData.pasture_org_id) {
    // console.log('formData', !formData.customer_id, new_data, adminFaEarconListApi)
    const res = await spForageSpecsListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      return res
    }
  } else {
    ElMessage({
      message: '请选择牧场',
      type: 'warning'
    })
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
}
/****************************** 函数方法 end ******************************/
const editRef = ref()
// const Rfidend = ref()
const save = async () => {
  dialogVisible.value = false
  await getPastureSee()
}
//   const edit = unref(editRef)
//   switch (actionType.value) {
//     case 'add':
//       // console.log(await edit.rfid, 'eeee')
//       for (let index = 0; index < (await edit.rfid.length); index++) {
//         console.log(await edit.rfid[index], 'eeee')
//       }
//       data.value.rfid = await edit.rfid
//       dialogVisible.value = false
//       saveLoading.value = false
//       break
//     case 'mu':
//       // console.log(await edit.save(), await edit.aaa, 'eeee')
//       dialogVisible.value = false
//       saveLoading.value = false
//       break
//     default:
//       console.log('未知类型')
//   }
// }

/****************************** 返回参数 start ******************************/
// defineExpose({
//   elFormRef,
//   getFormData: methods.getFormData
// })
/****************************** 返回参数 end ******************************/

/****************************** 初始化 start ******************************/
const init = async () => {
  // 调用查看接口查询数据
  await getPastureSee()
  // data.value.detailed = []
  data.value.rfid = []
}
init()
/****************************** 初始化 end ******************************/
</script>

<template>
  <ContentWrap title="明细数据">
    <div class="mb-10px">
      <!-- <ElButton type="primary">新增行</ElButton> -->
      <ElButton circle :icon="icon" @click="action('add_d', '1')" title="新增行" />
    </div>
    <Table :columns="d_columns" :data="data.detailed" :selection="false" :border="true">
      <template #forage_id="{ row }">
        <EarconRefer
          v-model="row.forage_id"
          :getListApi="getDanganListApi"
          :response="{ count: 'count', data: 'data' }"
          title="选择档案（双击选择）"
          nameField="name"
          relNameField="name"
          valueField="id"
          :crudSchemas="[
            // { field: 'is_selected', label: '是否已选', search: { show: false }, width: 280 },
            { field: 'name', label: '档案名称', search: { show: true } },
            { field: 'pasture_org_name', label: '所属牧场', search: { show: true } }
          ]"
          :modelName="row.state == 1 ? row.name : row.forage_name"
          :selected="data.detailed"
        />
      </template>

      <template #forage_specs_id="{ row }">
        <EarconRefer
          v-model="row.forage_specs_id"
          :getListApi="getGuigeListApi"
          :response="{ count: 'count', data: 'data' }"
          title="选择规格（双击选择）"
          nameField="name"
          relNameField="name"
          valueField="id"
          :crudSchemas="[
            // { field: 'is_selected', label: '是否已选', search: { show: false }, width: 280 },
            { field: 'name', label: '档案名称', search: { show: true } },
            { field: 'pasture_org_name', label: '所属牧场', search: { show: true } }
          ]"
          :modelName="row.state == 1 ? row.name : row.forage_specs_name"
          :selected="data.detailed"
        />
      </template>
      <template #apply_number="{ row }">
        <ElInput v-model="row.apply_number" />
      </template>

      <template #actual_number="{ row }">
        <ElInput v-model="row.actual_number" v-if="row.rfid_number == 0" />
      </template>

      <template #amount="{ row }">
        <ElInput v-model="row.amount" v-if="props.currentRow.type == 1" />
      </template>
      <!-- <template #state="{ row }">
        <ElSelectV2 v-model="row.state" :options="dict.quarantine_order_state" />
      </template> -->

      <!-- <template #creation_time="{ row }">
        <ElDatePicker v-model="row.creation_time" style="width: 150px" valueFormat="YYYY-MM-DD" />
      </template> -->

      <template #action="{ row }">
        <ElButton
          v-if="row.state !== 1"
          circle
          :icon="icon"
          @click="action('add+', row)"
          title="Rfid"
        />
        <ElButton
          circle
          v-if="row.state !== 1"
          :icon="iconSee"
          @click="action('add', row)"
          title="Rfid"
        />

        <ElButton
          circle
          v-if="row.state !== 1"
          :icon="iconDel"
          @click="action('del_d', row)"
          title="删除行"
        />
        <ElButton
          circle
          v-if="row.state == 1"
          :icon="iconOk"
          @click="action('ok', row)"
          title="确定添加"
        />

        <ElButton
          circle
          v-if="row.rfid_number == 0"
          :icon="iconOk"
          @click="action('rfid_number', row)"
          title="确定实际数量"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <!-- <Edit v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <Edit v-if="actionType == 'add'" ref="editRef" />

    <See v-if="actionType == 'see'" :id="tableObject.currentRow.id" /> -->

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->
    <Food v-if="actionType == 'add'" ref="editRef" :rowid="Rfid" :da="data" />
    <!-- <Mu v-if="actionType == 'mu'" ref="editRef" /> -->
    <template #footer>
      <!-- <ElButton v-if="actionType == 'add'" type="primary" :loading="saveLoading" @click="save()">
        保存
      </ElButton> -->
      <ElButton @click="save()">关闭</ElButton>
    </template>
  </Dialog>
</template>
